﻿using UnityEngine;
using System;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace Gdmec.Timer

{
    public class TimeManager : MonoBehaviour
    {
        public static TimeManager Instance { get; private set; }
        private Queue<Timer> timer_pools = new Queue<Timer>();
        private List<Timer> act_list = new List<Timer>();
        public static float NowTime { get { return Time.realtimeSinceStartup; } }
        void Awake()
        {
            Instance = this;
        }

        void OnDestroy()
        {
            Instance = null;
        }

        public Timer GetTimer()
        {
            if (timer_pools.Count > 0)
            {
                return timer_pools.Dequeue();
            }
            return new Timer();
        }

        public static void Add(float endTime, float cdTime = 0, Action onCall = null)
        {
            var timer = Instance.GetTimer();
            timer.endTime = endTime;
            timer.cdTime = cdTime;
            timer.onCall = onCall;
            Instance.act_list.Add(timer);
        }

        private Timer tempTimer;
        void Update()
        {
            if (Instance.act_list.Count > 0)
            {
                var list = act_list.ToList();
                for (int i = 0; i < list.Count; i++)
                {
                    tempTimer = act_list[i];
                    if (Time.realtimeSinceStartup >= tempTimer.endTime)
                    {
                        tempTimer.onCall?.Invoke();
                        if (tempTimer.cdTime > 0)
                        {
                            tempTimer.endTime = Time.realtimeSinceStartup + tempTimer.cdTime;
                        }
                        else
                        {
                            act_list.Remove(tempTimer);
                            tempTimer.cdTime = 0;
                            tempTimer.endTime = 0;
                            tempTimer.onCall = null;
                            timer_pools.Enqueue(tempTimer);
                        }
                    }
                }
                tempTimer = null;
            }
        }
    }

    public class Timer
    {
        public float endTime = 0;
        public float cdTime = 0;
        public System.Action onCall;
    }
}
